package cn.wowjoy.office.materialmanage.inventoryReport;

import android.arch.lifecycle.Observer;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.shizhefei.view.indicator.IndicatorViewPager;
import com.shizhefei.view.indicator.slidebar.ColorBar;
import com.shizhefei.view.indicator.transition.OnTransitionTextListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseActivity;
import cn.wowjoy.office.baselivedata.appbase.NewBaseFragment;
import cn.wowjoy.office.common.adapter.TabIndicatorActivityAdapter;
import cn.wowjoy.office.common.widget.CommonDialog;
import cn.wowjoy.office.common.widget.CreateDialog;
import cn.wowjoy.office.common.widget.MDialog;
import cn.wowjoy.office.common.widget.timepicker.TimePickerView;
import cn.wowjoy.office.data.remote.ResultEmpty;
import cn.wowjoy.office.data.response.CheckerResponse;
import cn.wowjoy.office.data.response.StockRecordResponse;
import cn.wowjoy.office.databinding.ActivityAddReport2Binding;
import cn.wowjoy.office.materialmanage.addReport.StockRecordeActivity;
import cn.wowjoy.office.utils.ToastUtil;

@Route(path = "/materialmanage/inventoryReport/addreport2")
public class AddReport2Activity extends NewBaseActivity<ActivityAddReport2Binding,InventoryReportViewModel> implements View.OnClickListener {

    @Autowired
    String headCode;
    @Autowired
    boolean isCheckFailed;
    @Autowired
    boolean isCheckSuccess;

    @Autowired
    boolean isCanNotEdit;

    private static final int REQUEST_CODE = 1111;
    private static final int REQUEST_CODE1 = 1011;
    private static final int REQUEST_CODE2 = 1012;
    private static final int REQUEST_CODE3 = 1013;
    private TimePickerView pvTime;
    private List<String> titles;
    private List<NewBaseFragment> fragments;
    private IndicatorViewPager indicatorViewPager;
    private TabIndicatorActivityAdapter mTabIndicatorActivityAdapter;
    private RecordFragment allFragment;
    private RecordProfitFragment enteredFragment;
    private RecordLossesFragment notEnteredFragment;
    private CommonDialog checkNoticeDialog;
    private CommonDialog checkFailedDialog;
    private List<CheckerResponse> submitCheckers;
    private StringBuilder checkers;

    private MDialog waitDialog;

    private void clearDialog(){
        if (waitDialog != null ){
            waitDialog.dismiss();
            waitDialog = null;
        }
    }


    private void showCheckNoticDialog(){
        if (null == checkNoticeDialog)
            checkNoticeDialog = new CommonDialog.Builder()
                    .setTitle("提示")
                    .setKey("确认提交审核吗？",0xff333333,13.33f)
                    .setContent("                   确认提交审核吗？\n                   提交审核后报告不可修改：")
                    .setContentGravity(Gravity.CENTER|Gravity.LEFT)
                    .setCancelBtn("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            checkNoticeDialog.dismissAllowingStateLoss();
                        }
                    })
                    .setConfirmBtn("确定", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            checkNoticeDialog.dismissAllowingStateLoss();
                            //请求审核接口
                            viewModel.pdaSubmit(submitCheckers);
                        }
                    })
                    .create();
        checkNoticeDialog.show(getSupportFragmentManager(),null);
    }

    private void showCheckFailedDialog(){
        checkFailedDialog = new CommonDialog.Builder()
                .setTitle("提交失败")
                .setContentColor(R.color.appText)
                .setContent("当前还有未填写的盘点报告，请填写完成后提交")
                .showCancel(false)
                .setConfirmBtn("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        checkFailedDialog.dismissAllowingStateLoss();
                    }
                })
                .create();
    }
    @Override
    protected Class<InventoryReportViewModel> getViewModel() {
        return InventoryReportViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_report2;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        ARouter.getInstance().inject(this);
        binding.setViewmodel(viewModel);
        viewModel.setHeadCode(headCode);
        submitCheckers = new ArrayList<>();
        if (!isCanNotEdit)
            initTimePicker();
        initView();
        initData();
        initVP();
        initObserver();
        viewModel.getBasic();
        isReadySubmit();

    }

    @Override
    protected ViewGroup getErrorViewRoot() {
        return binding.errorContent;
    }

    @Override
    protected void refreshError() {
        super.refreshError();
        viewModel.getBasic();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    private void initObserver(){
        viewModel.isReadySubmit.observe(this, new Observer<LiveDataWrapper<String>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<String> resultEmptyLiveDataWrapper) {
                switch (resultEmptyLiveDataWrapper.status){
                    case LOADING:
                        break;
                    case SUCCESS:
                        if (TextUtils.equals("y",resultEmptyLiveDataWrapper.data)){
                            binding.check.setEnabled(true);
                        } else {
                            binding.check.setEnabled(false);
                        }

                        break;
                    case ERROR:
                       handleException(resultEmptyLiveDataWrapper.error,false);
                        break;
                }
            }
        });
        viewModel.basicResult.observe(this, new Observer<LiveDataWrapper<StockRecordResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<StockRecordResponse> stockRecordResponseLiveDataWrapper) {
                switch (stockRecordResponseLiveDataWrapper.status){
                    case LOADING:
                        clearDialog();
                        waitDialog = CreateDialog.waitingDialog(AddReport2Activity.this);
                        break;
                    case SUCCESS:
                        clearDialog();
                        setModel(stockRecordResponseLiveDataWrapper.data);
                        break;
                    case ERROR:
                        clearDialog();
                        handleException(stockRecordResponseLiveDataWrapper.error,true);

                        break;
                }
            }
        });
        viewModel.pdaSubmit.observe(this, new Observer<LiveDataWrapper<String>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<String> resultEmptyLiveDataWrapper) {
                switch (resultEmptyLiveDataWrapper.status){
                    case LOADING:
                        clearDialog();
                        waitDialog = CreateDialog.waitingDialog(AddReport2Activity.this);
                        break;
                    case SUCCESS:
                        clearDialog();
                        ToastUtil.toastImage(getApplication().getApplicationContext(),"提交成功",-1);
                        break;
                    case ERROR:
                        clearDialog();
                        if (resultEmptyLiveDataWrapper.error.getMessage().contains("当前还有为填写的盘点报告，请填写完成后提交")){
                            showCheckFailedDialog();
                        } else {
                            handleException(resultEmptyLiveDataWrapper.error,false);
                        }

                        break;
                }
            }
        });

    }
    private void initTimePicker(){
        //控制时间范围(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
        //因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        startDate.set(2000, 0, 1);
        Calendar endDate = Calendar.getInstance();
        endDate.set(3000, 11, 31);
        //时间选择器
        pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                // 这里回调过来的v,就是show()方法里面所添加的 View 参数，如果show的时候没有添加参数，v则为null
                /*btn_Time.setText(getTime(date));*/
                binding.inventoryTime.setText(getTime(date));
                viewModel.setCheckDate(getTime(date));
                Calendar cal=Calendar.getInstance();
                cal.setTime(date);
                pvTime.setDate(cal);

            }
        })
                //年月日时分秒 的显示与否，不设置则默认全部显示
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("年", "月", "日", "", "", "")
                .isCenterLabel(true)
                .isCyclic(true)
                .setDividerColor(0xFFDCDCDC)
                .setContentSize(13)
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setTextColorCenter(0xFF369FF1)
                .setTextColorOut(0xFF666666)
//                .setBackgroundId(0x00FFFFFF) //设置外部遮罩颜色
                .setDecorView(null)
                .build();

    }
    private String getCurrentTime(){
        SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        return str;
    }

    private void refreshStaffTV(){
        if (null != checkers){
            binding.staff.setText(checkers.toString().trim());
        } else {
            binding.staff.setText("无");
        }
    }
    private void setModel(StockRecordResponse recordResponse){
        binding.setModel(recordResponse);
        checkers = recordResponse.initCheckers();
        refreshStaffTV();
        if (Double.parseDouble(recordResponse.getProfit()) == 0){
            binding.inventoryProfit.setTextColor(getResources().getColor(R.color.appText10));
        } else if (Double.parseDouble(recordResponse.getProfit()) < 0){
            binding.inventoryProfit.setTextColor(getResources().getColor(R.color.menu_look_error));
        } else {
            binding.inventoryProfit.setTextColor(getResources().getColor(R.color.decorateGreenHighLight));
        }
        if (Double.parseDouble(recordResponse.getLoss()) == 0){
            binding.inventoryLosses.setTextColor(getResources().getColor(R.color.appText10));
        } else if (Double.parseDouble(recordResponse.getLoss()) < 0){
            binding.inventoryLosses.setTextColor(getResources().getColor(R.color.menu_look_error));
        } else {
            binding.inventoryLosses.setTextColor(getResources().getColor(R.color.decorateGreenHighLight));
        }
        if (Double.parseDouble(recordResponse.getTotal()) == 0){
            binding.totalMoney.setTextColor(getResources().getColor(R.color.appText10));
        } else if (Double.parseDouble(recordResponse.getTotal()) < 0){
            binding.totalMoney.setTextColor(getResources().getColor(R.color.menu_look_error));
        } else {
            binding.totalMoney.setTextColor(getResources().getColor(R.color.decorateGreenHighLight));
        }

    }
    private void initView(){
        if (isCheckFailed){
            binding.title.setText("审核失败");
            binding.check.setVisibility(View.GONE);
            binding.failNotice.setVisibility(View.VISIBLE);
        } else {
            binding.title.setText("添加盘点报告");
            binding.failNotice.setVisibility(View.GONE);
            if (isCanNotEdit){
                binding.check.setVisibility(View.GONE);
                binding.addStaff.setVisibility(View.GONE);
                binding.indateLimit.setVisibility(View.GONE);
            } else {
                binding.check.setVisibility(View.VISIBLE);
                binding.addStaff.setVisibility(View.VISIBLE);
                binding.indateLimit.setVisibility(View.VISIBLE);
            }

        }
        binding.back.setOnClickListener(this);
        binding.check.setOnClickListener(this);
        if (!isCanNotEdit)
            binding.inventoryTime.setOnClickListener(this);
        binding.addStaff.setOnClickListener(this);
    }

    private void initVP()
    {
        binding.tabIndicator.setScrollBar(new ColorBar(getApplicationContext(), getResources().getColor(R.color.view_line1), 4));//设置滚动条的颜色，及高度
        binding.tabIndicator.setOnTransitionListener(new OnTransitionTextListener().setColor(ContextCompat.getColor(this, R.color.appText14), ContextCompat.getColor(this, R.color.appText10)));
        indicatorViewPager = new IndicatorViewPager(binding.tabIndicator, binding.vp);
        mTabIndicatorActivityAdapter = new TabIndicatorActivityAdapter(getSupportFragmentManager());
        mTabIndicatorActivityAdapter.setData(titles, fragments);
        indicatorViewPager.setAdapter(mTabIndicatorActivityAdapter);
        binding.vp.setCanScroll(true);
        binding.vp.setOffscreenPageLimit(3);
    }
    private void initData() {
        titles = new ArrayList<>();
        titles.add("全部");
        titles.add("盘盈");
        titles.add("盘亏");
        fragments = new ArrayList<>();
        allFragment = RecordFragment.newInstance(headCode, null,isCanNotEdit);
        enteredFragment = RecordProfitFragment.newInstance(headCode, "y",isCanNotEdit);
        notEnteredFragment = RecordLossesFragment.newInstance(headCode, "n",isCanNotEdit);
        fragments.add(allFragment);
        fragments.add(enteredFragment);
        fragments.add(notEnteredFragment);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back:
                onBackPressed();
                break;
            case R.id.check:
                showCheckNoticDialog();
                break;
            case R.id.inventory_time:
                if (null != pvTime)
                    pvTime.show();
                break;
            case R.id.add_staff:
                ARouter.getInstance().build("/materialmanage/inventoryReport/staff")
                        .navigation(this,REQUEST_CODE);
                break;
        }
    }

    public void isReadySubmit(){
        viewModel.isReadySubmit();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        isReadySubmit();
        switch (requestCode){
            case REQUEST_CODE:
                if (null != data){
                    CheckerResponse checkerResponse = (CheckerResponse) data.getSerializableExtra("checker");
                    if (null != checkers){
                        checkers.append("、"+checkerResponse.getName()+"（"+checkerResponse.getNumber()+"）");
                    } else {
                        checkers = new StringBuilder();
                        checkers.append(checkerResponse.getName()+"（"+checkerResponse.getNumber()+"）");
                    }
                    refreshStaffTV();
                    submitCheckers.add(checkerResponse);
                }
                break;
            case REQUEST_CODE1:
                allFragment.onActivityResult(requestCode,resultCode,data);
                break;
            case REQUEST_CODE2:
                enteredFragment.onActivityResult(requestCode,resultCode,data);
                break;
            case REQUEST_CODE3:
                notEnteredFragment.onActivityResult(requestCode,resultCode,data);
                break;
        }
    }
}
